package com.ubs.web.diagnostic.core;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ubs.web.diagnostic.exception.DiagnosticException;

/**
 * Servlet implementation class AccountRegistrationServlet
 */
public abstract class DiagnosticRunnerServlet extends HttpServlet {
	private static final String SUITE_NAME_LABEL = "<h3><font color='blue'>%s</font></h3>";
	private static final long serialVersionUID = 1L;
	private static final String STEP_STARTING_MSG = "<li>%s test is starting... ";
	private static final String STEP_OK_MSG = "<font color='green'>done</font>";
	private static final String STEP_FAILED = "<font color='red'>failed:</font><br>";
	private static final String ERROR_MESSAGE = "%s: %s<br>";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DiagnosticRunnerServlet() {
        super();
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		runDiagnostic(request, response);
	}

	private void runDiagnostic(HttpServletRequest request, HttpServletResponse response) {
		ServletOutputStream out;
		try {
			out = response.getOutputStream();
			out.print("<html><body>");
			try {
				for(TestSuite suite : getTestSuites()) {
					out.print(String.format(SUITE_NAME_LABEL, suite.getSuiteName()));
					for(TestStep step : suite.getTestSteps()) {
						out.print(String.format(STEP_STARTING_MSG, step.getName()));
							step.testBody();
							out.print(STEP_OK_MSG);
					}
				}
			} catch (DiagnosticException e) {
				out.print(STEP_FAILED);
				out.print(String.format(ERROR_MESSAGE, e, e.getMessage()));
				printStackTrace(out, e.getStackTrace());
			}
			out.print("</body></html>");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	private void printStackTrace(ServletOutputStream out,
			StackTraceElement[] stackTrace) throws IOException {
			
		for(StackTraceElement element : stackTrace) {
			 out.print("<br>" + element.toString().replace("\t", "&nbsp;"));
		}
	}

	protected abstract List<TestSuite> getTestSuites();

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		runDiagnostic(request, response);
	}

}
